﻿using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;

namespace PageAdmin.Utils.ORM
{

    internal class BasicHelper
    {

        /// <summary>
        /// 是否是字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsStr(string str)
        {
            if (string.IsNullOrEmpty(str)) { return false; }
            string str1 = "abcdefghijklmnopqrstuvwxyz0123456789_";
            string str2 = str.ToLower();
            for (int i = 0; i < str2.Length; i++)
            {
                if (str1.IndexOf(str2[i]) == -1)
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 第一个字符大写
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static  string FirstCharUpper(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                if (str.Length > 1)
                {
                    str = str[0].ToString().ToUpper() + str.Substring(1, str.Length - 1);
                }
                else
                {
                    str = str.ToUpper();
                }
            }
            return str;
        }

        /// <summary>
        /// 深拷贝
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="isXmlSerializer"></param>
        /// <returns></returns>
        public static T DeepClone<T>(T obj, bool isXmlSerializer = true) where T : class
        {
            if (obj == null)
            {
                return null;
            }
            using (Stream stream = new MemoryStream())
            {
                if (isXmlSerializer)
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    serializer.Serialize(stream, obj);
                    stream.Seek(0, SeekOrigin.Begin);
                    return (T)serializer.Deserialize(stream);
                }
                else
                {
                    IFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(stream, obj);
                    stream.Seek(0, SeekOrigin.Begin);
                    return (T)formatter.Deserialize(stream);
                }

            }
        }
    }
}